// test5.ts

// 导入 AssemblyScript 标准库


// 导出内存
export const memory: Memory = new Memory({ initial: 1, maximum: 4 });

// 辅助函数：将数组写入共享内存
function writeArrayToSharedMemory(array: Array<i32>, sharedMemory: ArrayBuffer): i32 {
    const dv = new DataView(sharedMemory);
    const pointer = changetype<i32>(dv);
    for (let i = 0; i < array.length; i++) {
        dv.setInt32(pointer + (i << 2), array[i], true);
    }
    return pointer;
}

// 函数1：无参数传入传出，for循环1加到1000赋值数组2，作为baseline
export function baselineTest(): void {
    let array2: Array<i32> = new Array<i32>(1000);
    for (let i = 0; i < 1000; i++) {
        array2[i] = i + 1;
    }
}

// 函数2：无参数传入，for循环1到1000赋值给数组2，传出数组2
export function noInputWithOutput(): i32 {
    let array2: Array<i32> = new Array<i32>(1000);
    for (let i = 0; i < 1000; i++) {
        array2[i] = i + 1;
    }
    return writeArrayToSharedMemory(array2, idb.mem);
}

// 函数3：传入数组1，for循环1到1000赋值给数组2，这一步目的是控制变量，传出数组2
export function withInputAndOutput(array1: Array<i32>): i32 {
    let array2: Array<i32> = new Array<i32>(1000);
    for (let i = 0; i < 1000; i++) {
        array2[i] = i + 1;
    }
    return writeArrayToSharedMemory(array2, idb.mem);
}

// 函数4：传入数组1，for循环1到1000赋值给数组2，这一步目的是控制变量，无返回值
export function withInputNoOutput(array1: Array<i32>): void {
    let array2: Array<i32> = new Array<i32>(1000);
    for (let i = 0; i < 1000; i++) {
        array2[i] = i + 1;
    }
    writeArrayToSharedMemory(array2, idb.mem);
}